import {Component, ElementRef, ViewChild} from '@angular/core';
import {App, IonicPage, NavController} from 'ionic-angular';
import {PublicService} from "../../common/public.service";
import {DatePicker} from "@ionic-native/date-picker";
import {
  CARD_RECORD_URL, DELETE_FILL_VOLUME_URL, FILL_VOLUME_LIST_URL, FILL_VOLUME_START_URL, PRODUCT_LIST_URL,
  SERIES_LIST_URL, SET_GROUP_URL,
  STATION_LIST_URL
} from "../../providers/Constants";
import {HttpService} from "../../providers/HttpService";
import $ from 'jquery';
import {NativeAudio} from "@ionic-native/native-audio";

/**
 * 在上班前，班长需在此页面设置本班组上班时间，
 * 然后自动算出下班时间（可变更），
 * 班长可以扫描员工工作证二维码进行上班打卡，
 * 如果单个员工涉及多个工站，
 * 则点击增行按钮进行增行，
 * 对于个人计件的工站，
 * 可以选择工站计件的产品。
 */

@IonicPage()
@Component({
  selector: 'page-work-in',
  templateUrl: 'work-in.html',
})
export class WorkInPage {

  bzDate: string;//班组日期
  minDate: string;//最小日期
  bzSelect: string;//班组选择
  workInTime: string;//上班时间
  workOutTime: string;//下班时间

  //处理类型
  public handleTypes: Array<Object> = JSON.parse(localStorage.getItem("mpower-handleTypes"));
  public attendanceTypes: Array<Object> = JSON.parse(localStorage.getItem("mpower-attendanceTypes"));
  public workProcedures: Array<Object> = JSON.parse(localStorage.getItem("mpower-workProcedure"));

  //用户名
  personName: string = localStorage.getItem("mpower-personName");

  //设置默认值
  defaultHandleType: string = sessionStorage.getItem("defaultHandleType") ? sessionStorage.getItem("defaultHandleType") : null;
  defaultProduct: string = sessionStorage.getItem("defaultProduct") ? sessionStorage.getItem("defaultProduct") : null;
  defaultAttendanceType: string = sessionStorage.getItem("defaultAttendanceType") ? sessionStorage.getItem("defaultAttendanceType") : null;
  defaultProductSeries: string = sessionStorage.getItem("defaultProductSeries") ? sessionStorage.getItem("defaultProductSeries") : null;

  //扫描后把数据保存在这里
  public dataList: Array<Object> = [];
  //待提交数据
  public subDataList: Array<Object> = [];

  //上班打卡人数
  private startCount: number = 0;

  constructor(public navCtrl: NavController,
              public pub: PublicService,
              public datePicker: DatePicker,
              public app: App,
              private nativeAudio: NativeAudio,
              public element: ElementRef,
              private http: HttpService) {
  }

  ionViewDidLoad() {
    this.bzDate = sessionStorage.getItem("setWorkTime");
    if (!this.bzDate) {
      this.bzDate = this.pub.getDate(new Date(), 0);
    }
    this.workInTime = sessionStorage.getItem("setWorkInTime");
    this.workOutTime = sessionStorage.getItem("setWorkOutTime");
    this.bzSelect = sessionStorage.getItem("setBzSelect");

    if (sessionStorage.getItem("datalist")) {
      this.dataList = JSON.parse(sessionStorage.getItem("datalist"));
    }

    //初始化
    this.initTeam(sessionStorage.getItem("workProcedure"));

    if (this.defaultHandleType && this.defaultProductSeries) {
      this.defaultHandleTypeChange();
    }
    if (this.defaultProductSeries && this.defaultProduct) {
      this.defaultProductSeriesChange();
    }

    //加载音频文件
    this.nativeAudio.preloadSimple("conScanAudioSucId", "assets/audio/success.mp3");
    this.nativeAudio.preloadSimple("conScanAudioE001", "assets/audio/E001.mp3");
    this.nativeAudio.preloadSimple("conScanAudioE002", "assets/audio/E002.mp3");
    this.nativeAudio.preloadSimple("conScanAudioE003", "assets/audio/E003.mp3");
    this.nativeAudio.preloadSimple("conScanAudioE004", "assets/audio/E004.mp3");
    this.nativeAudio.preloadSimple("conScanAudioE005", "assets/audio/E005.mp3");
    this.nativeAudio.preloadSimple("conScanAudioE006", "assets/audio/E006.mp3");
    this.nativeAudio.preloadSimple("conScanAudioE007", "assets/audio/E007.mp3");
    this.nativeAudio.preloadSimple("conScanAudioE008", "assets/audio/E008.mp3");
    this.nativeAudio.preloadSimple("conScanAudioE009", "assets/audio/E009.mp3");
  }


  //刷新列表滚动到指定位置
  @ViewChild("tableScroll") tableScroll;

  /**
   * 打卡成功提示音
   */
  sucSound() {
    this.nativeAudio.play('conScanAudioSucId').then(() => {});
  }

  /**
   * 异常情况提示
   */
  errSound(erroCode: string) {
    this.nativeAudio.play('conScanAudio' + erroCode);
  }



  /**
   * 初始化班组数据
   * 根据工序初始化班组、班组日期
   */
  initTeam(wpcode: string) {
    if (this.workProcedures && this.workProcedures.length > 0) {
      for (let i = 0; i < this.workProcedures.length; i++) {
        if (wpcode == this.workProcedures[i]['code']) {
          let activeGroup = this.workProcedures[i]['activeGroup'];
          this.element.nativeElement.querySelector("#radioA").style.display = "none";
          this.element.nativeElement.querySelector("#spanA").style.display = "none";
          this.element.nativeElement.querySelector("#radioB").style.display = "none";
          this.element.nativeElement.querySelector("#spanB").style.display = "none";
          if (activeGroup.length == 1) {
            this.element.nativeElement.querySelector("#radio" + activeGroup[0]).style.display = "";
            this.element.nativeElement.querySelector("#span" + activeGroup[0]).style.display = "";
            this.bzSelect = activeGroup[0];
          } else {
            this.bzSelect = sessionStorage.getItem("setBzSelect") ? sessionStorage.getItem("setBzSelect") : activeGroup[0];
            this.element.nativeElement.querySelector("#radioA").style.display = "";
            this.element.nativeElement.querySelector("#spanA").style.display = "";
            this.element.nativeElement.querySelector("#radioB").style.display = "";
            this.element.nativeElement.querySelector("#spanB").style.display = "";
          }
        }
      }
    }
  }



  /**
   * 设置班组日期
   * 可选最近三天（今天前后各一天）
   */
  getDate() {
    this.datePicker.show({
      titleText: "",
      date: this.bzDate,
      mode: 'date',
      minDate: this.pub.getDate(new Date(this.bzDate), -1),
      maxDate: this.pub.getDate(new Date(this.bzDate), 1),
      is24Hour: true,
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_LIGHT
    }).then(
      date => {
        this.bzDate = this.pub.getDate(date, 0);
      },
      err => {
        console.log('Error occurred while getting date: ', err);
      }
    );
  }


  /**
   * 每次进入页面判断是否有未保存扫码后的结果
   */
  ionViewWillEnter() {
    if (sessionStorage.getItem("qrScannerTextIn")) {
      this.submitWork(sessionStorage.getItem("qrScannerTextIn"));
    } else {
      this.initList(0);
    }
  }

  /**
   * 上班时间
   */
  getWorkTnTime() {
    this.datePicker.show({
      titleText: "",
      date: new Date(),
      mode: 'time',
      is24Hour: true,
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_LIGHT
    }).then(
      date => {
        this.workInTime = this.pub.getYMDHM(date, 0);
        this.workOutTime = this.pub.getYMDHM(date, 11 * 60 * 60 * 1000);
      },
      err => {
        console.log('Error occurred while getting date: ', err);
      }
    );
  }

  /**
   * 下班时间
   */
  getWorkOutTime() {
    if (!this.workOutTime) {
      return;
    }
    this.datePicker.show({
      titleText: "",
      date: this.pub.stringToDate(this.workOutTime),
      mode: 'datetime',
      is24Hour: true,
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_LIGHT
    }).then(
      date => {
        this.workOutTime = this.pub.getYMDHM(date, 0);
      },
      err => {
        console.log('Error occurred while getting date: ', err);
      }
    );
  }

  /**
   * 上班设置
   */
  setWork() {
    if (!this.bzDate) {
      this.pub.presentLoadingToast("请设置班组日期");
      return;
    }
    if (!this.workInTime) {
      this.pub.presentLoadingToast("请设置上班时间");
      return;
    }
    if (!this.workOutTime) {
      this.pub.presentLoadingToast("请设置下班时间");
      return;
    }

    //判断下班时间不能小于上班时间
    let workOutTime_M = this.pub.stringToDate(this.workOutTime).getTime();
    let workInTime_M = this.pub.stringToDate(this.workInTime).getTime();

    if (!(workOutTime_M > workInTime_M)) {
      this.pub.presentLoadingToast("下班时间必须大于上班时间");
      return;
    }

    //判断班组数据是否更改，如果未更改则不提交服务器
    if (localStorage.getItem("groupId")) {
      if (sessionStorage.getItem("setWorkTime") == this.bzDate
        && sessionStorage.getItem("setBzSelect") == this.bzSelect
        && sessionStorage.getItem("setWorkInTime") == this.workInTime
        && sessionStorage.getItem("setWorkOutTime") == this.workOutTime) {
        this.pub.presentLoadingToast("设置成功");
        return;
      }
    }

    this.pub.presentCustomConfirm("确定设置吗？", "取消", "确定").then(() => {
      let params = {
        sessionId: sessionStorage.getItem("session"),
        fdDate: this.bzDate,
        fdType: this.bzSelect,
        fdProcedure: sessionStorage.getItem("workProcedure"),
        fdStartTime: this.workInTime,
        fdEndTime: this.workOutTime
      };
      this.http.get(SERVER_URL + SET_GROUP_URL, '&', params, true).then(res => {
        if (res.success) {
          sessionStorage.setItem("setWorkTime", res.groupSetInfo.fdDate);
          sessionStorage.setItem("setWorkInTime", res.groupSetInfo.fdStartTime);
          sessionStorage.setItem("setWorkOutTime", res.groupSetInfo.fdEndTime);
          sessionStorage.setItem("setBzSelect", res.groupSetInfo.fdType);
          sessionStorage.setItem("workProcedure", res.groupSetInfo.fdProcedure);

          this.bzDate = res.groupSetInfo.fdDate;
          this.bzSelect = res.groupSetInfo.fdType;
          this.workInTime = res.groupSetInfo.fdStartTime;
          this.workOutTime = res.groupSetInfo.fdEndTime;
          for (let i = 0; i < this.workProcedures.length; i++) {
            if (this.workProcedures[i]["code"] == res.groupSetInfo.fdProcedure) {
              localStorage.setItem("workProcedureName", this.workProcedures[i]["name"]);
            }
          }
          localStorage.setItem("groupId", res.groupId);
          this.pub.presentLoadingToast(res.msg);
          this.getHandleTypes();
        } else {
          this.pub.presentLoadingToast(res.msg);
          if (res.timeout) {
            setTimeout(() => {
              this.app.getRootNav().setRoot('LoginPage');
            }, 1500);
          }
        }
      });
    }).catch(() => {
    });


  }


  /**
   * 工站类型
   */
  getHandleTypes() {
    let params = {sessionId: sessionStorage.getItem("session"), groupId: localStorage.getItem("groupId")};
    this.http.get(SERVER_URL + STATION_LIST_URL, '&', params, false).then(res => {
      if (res.success) {
        localStorage.setItem("mpower-handleTypes", JSON.stringify(res.data.stations));
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }

  /**
   * 扫码二维码
   */
  scanner() {
    var setWorkTime = sessionStorage.getItem("setWorkTime");
    if (setWorkTime == this.bzDate) {
      this.navCtrl.push("ScanPage", {type: "start"});
    } else {
      this.pub.presentLoadingToast("请确认设置上下班时间");
    }
  }

  /**
   * 提交考勤
   * 如果设置过默认值，则直接提交数据，否则不提交数据
   * @param userCode
   */
  submitWork(userCode: string): Promise<any> {
    let params = {
      sessionId: sessionStorage.getItem("session"),
      groupId: localStorage.getItem("groupId"),
      persionNum: userCode,
      cardType: 'start'
    };
    this.http.get(SERVER_URL + CARD_RECORD_URL, '&', params, false).then(res => {
      if (res.success) {
        if (!this.usbFlag) {
          this.pub.presentLoadingToast(res.msg);
        }
        sessionStorage.removeItem("qrScannerTextIn");
        this.sucSound();
        //默认是设置的默认值
        if (this.defaultHandleType || this.defaultAttendanceType || this.defaultProductSeries || this.defaultProduct || res.data.mapLast) {
          this.subDataList = [];
          if (this.defaultHandleType || this.defaultAttendanceType || this.defaultProductSeries || this.defaultProduct) {
            this.subDataList.push({
              id: "",
              fdUserId: res.data.persionId,
              fdStationId: this.defaultHandleType ? this.defaultHandleType : "",
              fdKqType: this.defaultAttendanceType ? this.defaultAttendanceType : "",
              fdSeriesId: this.defaultProductSeries ? this.defaultProductSeries : "",
              fdProductId: this.defaultProduct ? this.defaultProduct : "",
              isSource: 0//是否是源（非增行项）0：是，1：否
            });
          } else {
            this.subDataList.push({
              id: "",
              fdUserId: res.data.persionId,
              fdStationId: res.data.mapLast.FDSTATIONID ? res.data.mapLast.FDSTATIONID : "",
              fdKqType: res.data.mapLast.FDKQTYPE ? res.data.mapLast.FDKQTYPE : "",
              fdSeriesId: res.data.mapLast.FDSERIESID ? res.data.mapLast.FDSERIESID : "",
              fdProductId: res.data.mapLast.FDPRODUCTID ? res.data.mapLast.FDPRODUCTID : "",
              isSource: 0//是否是源（非增行项）0：是，1：否
            });
          }
          this.submitVolume(0);
        } else {
          this.initList(0);
        }
      } else {
        sessionStorage.removeItem("qrScannerTextIn");
        this.errSound(res.erroCode);
        if (!this.usbFlag) {
          this.pub.presentLoadingToast(res.msg);
        }
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    })
    return new Promise((resolve, reject) => {
      resolve();
      reject();
    });
  }

  /**
   * 设置默认值
   */
  setDefaults() {
    if (this.defaultHandleType) {
      sessionStorage.setItem("defaultHandleType", this.defaultHandleType);
    } else {
      sessionStorage.removeItem("defaultHandleType");
    }
    if (this.defaultAttendanceType) {
      sessionStorage.setItem("defaultAttendanceType", this.defaultAttendanceType);
    } else {
      sessionStorage.removeItem("defaultAttendanceType");
    }
    if (this.defaultProduct) {
      sessionStorage.setItem("defaultProduct", this.defaultProduct);
    } else {
      sessionStorage.removeItem("defaultProduct");
    }
    if (this.defaultProductSeries) {
      sessionStorage.setItem("defaultProductSeries", this.defaultProductSeries);
    } else {
      sessionStorage.removeItem("defaultProductSeries");
    }
  }

  /**
   * 清除默认设置
   */
  clearDefaults() {
    this.defaultHandleType = null;
    this.defaultProduct = null;
    this.defaultAttendanceType = null;
    this.defaultProductSeries = null;
    sessionStorage.removeItem("defaultHandleType");
    sessionStorage.removeItem("defaultProduct");
    sessionStorage.removeItem("defaultAttendanceType");
    sessionStorage.removeItem("defaultProductSeries");
  }

  /**
   * 复制行
   * 插入到当前行的下面
   */
  copyRow(persionId, userCode, index) {
    if (this.hasUpdating) {
      this.pub.presentLoadingToast("请先保存编辑的数据");
      return;
    }
    let table_body = document.getElementById("tableBodys");
    let count = 0;
    for (let i = 0; i < table_body.children.length; i++) {
      if (table_body.children[i].id.indexOf(userCode) > -1) {
        count++;
      }
    }
    let procedureId = sessionStorage.getItem("workProcedure");
    let procedureName = sessionStorage.getItem("workProcedureName");
    let branchFactoryName = sessionStorage.getItem("fdDeptName");
    //首先获取当前行已经被增行次数，设置id为 id+_n
    let newRowId = userCode + "_" + count;
    if (this.dataList.length > 0) {
      for (let i = 0; i < this.dataList.length; i++) {
        if (this.dataList[i]['persionNum'] == userCode) {
          //同时保持到dataList中
          this.dataList.splice(index + 1, 0, {
            id: newRowId,
            branchFactoryName: branchFactoryName,
            procedureId: procedureId,//工序id
            procedureName: procedureName,
            persionId: persionId,//员工id
            persionNum: userCode,
            cardStart: this.dataList[i]['cardStart'],
            persionName: this.dataList[i]['persionName'],
            handleType: null,
            product: null,
            series: null,//产品系列
            attendanceType: null,//考勤类型
            isSource: 1//是否是源（非增行项）0：是，1：否
          });
          break;
        }
      }
    }
  }

  /**
   * 删除行
   * @param id
   */
  delRow(id: string, personCode: string, personid: string, isSource: string) {
    this.pub.presentCustomConfirm("确定删除改行吗？", "取消", "确定").then(() => {
      if (isSource == '1') {//增行项（未提交）
        for (let i = 0; i < this.dataList.length; i++) {
          if (this.dataList[i]['id'] == id && this.dataList[i]['persionId'] == personid) {
            this.dataList.splice(i, 1);
            break;
          }
        }
        for (let i = 0; i < this.subDataList.length; i++) {
          if (this.subDataList[i]['id'] == id && this.subDataList[i]['fdUserId'] == personid) {
            this.subDataList.splice(i, 1);
            break;
          }
        }
      } else {
        if (id) {//如果存在，则需要提交到服务器清除数据，否则本地清除数据
          let params = {
            sessionId: sessionStorage.getItem("session"),
            groupId: localStorage.getItem("groupId"),
            id: id
          };
          this.http.get(SERVER_URL + DELETE_FILL_VOLUME_URL, '&', params, false).then(res => {
            if (res.success) {
              this.initList(0);//重新加载列表
              this.pub.presentLoadingToast("删除成功");
            } else {
              this.pub.presentLoadingToast(res.msg);
              if (res.timeout) {
                setTimeout(() => {
                  this.app.getRootNav().setRoot('LoginPage');
                }, 1500);
              }
            }
          });
        } else {
          document.getElementById(personCode + "AttType")["value"] = "";
          document.getElementById(personCode + "handleType")["value"] = "";
          document.getElementById(personCode + "Series")["value"] = "";
          document.getElementById(personCode + "product")["value"] = "";
          for (let i = 0; i < this.subDataList.length; i++) {
            if (this.subDataList[i]['id'] == id && this.subDataList[i]['fdUserId'] == personid) {
              this.subDataList[i]["fdStationId"] = "";
              this.subDataList[i]["fdKqType"] = "";
              this.subDataList[i]["fdSeriesId"] = "";
              this.subDataList[i]["fdProductId"] = "";
              break;
            }
          }
        }
      }
      this.hasUpdating = false;
      this.personId = "";
      this.rowid = "";
    }).catch(() => {
    });
  }


  defaultProductSeriess: Array<Object> = [];

  /**
   * 选择工站，动态改变产品系列
   * 级联关系
   */
  defaultHandleTypeChange() {
    let params = {
      sessionId: sessionStorage.getItem("session"),
      stationCode: this.defaultHandleType
    };
    this.http.get(SERVER_URL + SERIES_LIST_URL, '&', params, false).then(res => {
      if (res.success) {
        this.defaultProductSeriess = res.data.seriesList;
        this.defaultProductSeries = null;
        this.defaultProduct = null;
        sessionStorage.removeItem("defaultProduct");
        sessionStorage.removeItem("defaultProductSeries");
        this.setDefaults();
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }

  defaultProductLists: Array<Object> = [];

  /**
   * 产品列表
   */
  defaultProductSeriesChange() {
    let params = {sessionId: sessionStorage.getItem("session"), seriesCode: this.defaultProductSeries};
    this.http.get(SERVER_URL + PRODUCT_LIST_URL, '&', params, false).then(res => {
      if (res.success) {
        this.defaultProductLists = res.data.productList;
        this.defaultProduct = null;
        sessionStorage.removeItem("defaultProduct");
        this.setDefaults();
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }


  /**
   * 初始化列表
   * 在每次进入该页面时调用：
   * 1、进入该页面；
   * 2、扫码后返回该页面；
   *
   * 扫码时提交其他数据
   * 都是服务器端最新数据
   * index:列表当前定位行
   */
  initList(index:number): Promise<any> {
    this.dataList = [];
    this.subDataList = [];
    let procedureId = sessionStorage.getItem("workProcedure");
    let procedureName = sessionStorage.getItem("workProcedureName");
    let branchFactoryId = sessionStorage.getItem("fdDeptId");
    let branchFactoryName = sessionStorage.getItem("fdDeptName");
    let params = {
      sessionId: sessionStorage.getItem("session"),
      groupId: localStorage.getItem("groupId")
    };
    this.http.get(SERVER_URL + FILL_VOLUME_LIST_URL, '&', params, false).then(res => {
      if (res.success) {
        if (res.data.fillVolumeList) {
          for (let i = 0; i < res.data.fillVolumeList.length; i++) {
            let data = res.data.fillVolumeList[i];
            var obj = {
              id: data.ID ? data.ID : "",//id
              persionId: data.FDUSERID,//员工id
              persionNum: data.FDUSERNUM,//工号
              persionName: data.FDUSERNAME,//姓名
              procedureId: procedureId,//工序id
              procedureName: procedureName,//工序名称
              branchFactoryId: branchFactoryId,//工厂id
              branchFactoryName: branchFactoryName,//工厂
              handleType: data.FDSTATIONID,//工站
              series: data.FDSERIESID,//产品系列
              seriesName: data.FDSERIESNAME,//产品系列
              productId: data.FDPRODUCTID,//产品
              proName: data.FDPRONAME,
              attendanceType: data.FDKQTYPE,//考勤类型
              workTime: data.FDWORKTIME,//工作时长
              inoutput: data.FDINOUTPUT,//产量
              isSystem: data.FDISSYSTEM,//是否系统分配产量
              teamId: data.FDTEAMID,//班组id
              cardStart: data.FDCARDSTART,//上班打卡时间
              isSource: 0//是否是源（非增行项）0：是，1：否
            };
            this.dataList.push(obj);
          }
        }
        this.startCount = res.data.startCount;
      } else {
        if (!this.usbFlag) {
          this.pub.presentLoadingToast(res.msg);
        }
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
    return new Promise((resolve, reject) => {
      resolve(index);
      reject();
    });
  }

  productSeries: Array<Object> = [];

  /**
   * 选择工站，动态改变产品系列
   * 级联关系
   */
  public handleTypeChange(seriesId: string) {
    let handleType = document.getElementById("handleType")["value"];
    let params = {
      sessionId: sessionStorage.getItem("session"),
      stationCode: handleType
    };
    this.http.get(SERVER_URL + SERIES_LIST_URL, '&', params, false).then(res => {
      if (res.success) {
        this.productSeries = res.data.seriesList;
        let select = document.getElementById("productSeries");
        if (select && select['options']) {
          select['options'].length = 0;
          select['options'].add(new Option("请选择", ""));
          for (let i = 0; i < this.productSeries.length; i++) {
            if (this.productSeries[i]['CODE'] == seriesId) {
              select['options'].add(new Option(this.productSeries[i]['NAME'], this.productSeries[i]['CODE'], true, true));
            } else {
              select['options'].add(new Option(this.productSeries[i]['NAME'], this.productSeries[i]['CODE']));
            }
          }
        }
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }

  productLists: Array<Object> = [];

  /**
   * 产品列表
   */
  productSeriesChange(productSeriesId: string, productId: string) {
    if (productSeriesId == "") {
      productSeriesId = document.getElementById("productSeries")["value"];
    }
    let params = {
      sessionId: sessionStorage.getItem("session"),
      seriesCode: productSeriesId
    };
    this.http.get(SERVER_URL + PRODUCT_LIST_URL, '&', params, false).then(res => {
      if (res.success) {
        this.productLists = res.data.productList;
        let select = document.getElementById("product");
        if (select && select['options']) {
          select['options'].length = 0;
          select['options'].add(new Option("请选择", ""));
          for (let i = 0; i < this.productLists.length; i++) {
            if (this.productLists[i]['PRODUCT_CODE'] == productId) {
              select['options'].add(new Option(this.productLists[i]['PRODUCT_NAME'], this.productLists[i]['PRODUCT_CODE'], true, true));
            } else {
              select['options'].add(new Option(this.productLists[i]['PRODUCT_NAME'], this.productLists[i]['PRODUCT_CODE']));
            }
          }
        }
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }

  /**
   * 提交工站产品数据
   * 获取页面上所有表单数据
   * index:保存后定位到当前行
   */
  submitVolume(index:number) {
    let sb_subDataList = this.subDataList;
    if (sb_subDataList.length > 0) {//清除增行的id值
      for (let i = 0; i < sb_subDataList.length; i++) {
        if (sb_subDataList[i]["isSource"] == 1) {
          sb_subDataList[i]["id"] = "";
        }
      }
    }
    let params = {
      sessionId: sessionStorage.getItem("session"),
      groupId: localStorage.getItem("groupId"),
      jsonList: JSON.stringify(sb_subDataList)
    };
    this.http.post(SERVER_URL + FILL_VOLUME_START_URL, '&', params, false).then(res => {
      if (res.success) {
        if (!this.usbFlag) {
          this.pub.presentLoadingToast("提交成功");
        }
        this.hasUpdating = false;
        this.personId = "";
        this.rowid = "";
        this.initList(0);
       /* this.initList(index).then((index)=>{
          this.tableScroll.nativeElement.scrollTo(0,index*12.5*2.5);
        });*/
      } else {
        if (!this.usbFlag) {
          this.pub.presentLoadingToast(res.msg);
        }
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }


  hasUpdating: boolean = false;
  personId: string = "";
  rowid: string = "";

  /**
   * 修改行数据
   * @param id
   * @param persionId
   * @param isSource
   * @param attendanceType 考勤
   * @param handleType 工站
   * @param series 系列
   * @param productId 产品
   */
  updateRow(id, persionId, isSource, attendanceType, handleType, series, productId) {
    if (this.hasUpdating) {
      this.pub.presentLoadingToast("同时只能编辑一条记录");
      return;
    }
    this.hasUpdating = true;
    this.personId = persionId;
    this.rowid = id;
    //考勤
    let att = `<select id="attendanceType">
        <option value="">请选择</option>`;
    for (let i = 0; i < this.attendanceTypes.length; i++) {
      if (this.attendanceTypes[i]['code'] == attendanceType) {
        att += `<option value="` + this.attendanceTypes[i]['code'] + `" selected>` + this.attendanceTypes[i]['name'] + ` </option>`;
      } else {
        att += `<option value="` + this.attendanceTypes[i]['code'] + `">` + this.attendanceTypes[i]['name'] + ` </option>`;
      }
    }
    att += `</select>`;

    //工站
    let Handle = `<select id="handleType" >
       <option value="">请选择</option>`;
    for (let i = 0; i < this.handleTypes.length; i++) {
      if (this.handleTypes[i]['code'] == handleType) {
        Handle += `<option value="` + this.handleTypes[i]['code'] + `" selected>` + this.handleTypes[i]['name'] + ` </option>`;
      } else {
        Handle += `<option value="` + this.handleTypes[i]['code'] + `">` + this.handleTypes[i]['name'] + ` </option>`;
      }
    }
    Handle += `</select>`;

    //产品系列
    let Series = `<select id="productSeries" ><option value="">请选择</option>`;
    for (let i = 0; i < this.productSeries.length; i++) {
      if (this.productSeries[i]['CODE'] == series) {
        Series += `<option value="` + this.productSeries[i]['CODE'] + `" selected>` + this.productSeries[i]['NAME'] + ` </option>`;
      } else {
        Series += `<option value="` + this.productSeries[i]['CODE'] + `">` + this.productSeries[i]['NAME'] + ` </option>`;
      }
    }
    Series += `</select>`;

    //产品
    let Pro = `<select id="product"><option value="">请选择</option>`;
    for (let i = 0; i < this.productLists.length; i++) {
      if (this.productLists[i]['PRODUCT_CODE'] == productId) {
        Pro += `<option value="` + this.productLists[i]['PRODUCT_CODE'] + `" selected>` + this.productLists[i]['PRODUCT_NAME'] + ` </option>`;
      } else {
        Pro += `<option value="` + this.productLists[i]['PRODUCT_CODE'] + `">` + this.productLists[i]['PRODUCT_NAME'] + ` </option>`;
      }
    }
    Pro += `</select>`;

    if (id) {
      let rows = document.getElementById(id).children;
      if (rows) {
        for (let i = 0; i < rows.length; i++) {
          if (rows[i]["id"] == persionId + "Att") {
            rows[i].innerHTML = att;
          }
          if (rows[i]["id"] == persionId + "Handle") {
            rows[i].innerHTML = Handle;
          }
          if (rows[i]["id"] == persionId + "Series") {
            rows[i].innerHTML = Series;
          }
          if (rows[i]["id"] == persionId + "Pro") {
            rows[i].innerHTML = Pro;
          }
        }
      }
    } else {
      document.getElementById(persionId + "Att").innerHTML = att;
      document.getElementById(persionId + "Handle").innerHTML = Handle;
      document.getElementById(persionId + "Series").innerHTML = Series;
      document.getElementById(persionId + "Pro").innerHTML = Pro;
    }

    this.handleTypeChange(series);
    this.productSeriesChange(series, productId);

    $("#handleType").on("change", () => {
      this.handleTypeChange(series);
    });

    $("#productSeries").on("change", () => {
      this.productSeriesChange("", productId);
    });
  }


  /**
   * 保存当前修改的数据
   * @param id 当前行id
   * @param persionId 考勤员工id
   * @param isSource 是否是元数据
   * @param index 序列号
   */
  saveRow(id, persionId, isSource,index) {
    this.subDataList = [];
    let fdStationId = document.getElementById("handleType")["value"];
    let fdKqType = document.getElementById("attendanceType")["value"];
    let fdSeriesId = document.getElementById("productSeries")["value"];
    let fdProductId = document.getElementById("product")["value"];

    //判断当前工站计件方式 *计件方式：personal 个人计件，group 集体计件*/
    //集体计件产品系列是非必填项
    //集体计件则个人产量无效，不需要录入
    let jobType = "personal";
    for (let i = 0; i < this.handleTypes.length; i++) {
      if (this.handleTypes[i]["code"] == fdStationId) {
        jobType = this.handleTypes[i]["jobType"];
      }
    }
    //默认是设置的默认值
    if (!fdKqType) {
      this.pub.presentLoadingToast("考勤类型是必填项");
      return;
    }
    if (!fdStationId) {
      this.pub.presentLoadingToast("工站是必填项");
      return;
    }
    if (!fdSeriesId && jobType == 'personal') {
      this.pub.presentLoadingToast("产品系列是必填项");
      return;
    }
    this.subDataList.push({
      id: id,
      fdUserId: persionId,
      fdStationId: fdStationId,
      fdKqType: fdKqType,
      fdSeriesId: fdSeriesId,
      fdProductId: fdProductId,
      isSource: isSource//是否是源（非增行项）0：是，1：否
    });
    this.submitVolume(index);
  }


  /**
   * 连续扫码
   */
  conScanner() {
    var setWorkTime = sessionStorage.getItem("setWorkTime");
    if (setWorkTime == this.bzDate) {
      this.navCtrl.push("ConScannerPage", {type: "start"});
    } else {
      this.pub.presentLoadingToast("请确认设置上下班时间");
    }
  }

  @ViewChild('scanText') scanTexts;

  usbFlag: boolean = false;

  /*  ionViewDidEnter() {
   setTimeout(() => {
   this.scanTexts.setFocus();//输入框获取焦点
   }, 150);
   }*/

  scanChange() {
    if (this.scanTexts && this.scanTexts.value) {
      this.submitWork(this.scanTexts.value).then(() => {
        this.scanTexts.value = "";
        setTimeout(() => {
          this.scanTexts.setFocus();//输入框获取焦点
        }, 150);
      }).catch(() => {
        this.scanTexts.value = "";
        setTimeout(() => {
          this.scanTexts.setFocus();//输入框获取焦点
        }, 150);
      });
    }
  }

  /**
   * 设置获取焦点，外部设备扫码
   */
  usbScanner() {
    this.usbFlag = true;
    this.scanTexts.setFocus();//输入框获取焦点
  }


}
